<?php


namespace app\admin\controller;


use app\constant\SubjectConst;
use app\helper\SubjectHelper;
use app\model\AdminSubject;
use app\model\AdminSubjectActive;
use app\util\ReturnCode;
use Exception;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;

class Subject extends Base
{
    /**
     * 根据id获取数据
     * @return array
     */
    public function get()
    {
        $id = request()->param('id');
        try {
            $model = new AdminSubject();
            $where = ['id' => $id];
            $where = $this->addTid($where);
            $model->where($where);
            $data = $model->find();
            return $this->buildSuccess($data);
        } catch (Exception $e) {
        }
        return $this->buildFailed(ReturnCode::INVALID, '获取数据失败');
    }

    public function save()
    {
        $postData = $this->request->post();
        $postData = $this->addTid($postData);
        $this->addTid($postData);
        if (isset($postData['id'])) {
            $result = AdminSubject::update($postData);
        } else {
            $result = AdminSubject::create($postData);
        }
        if ($result) {
            return $this->buildSuccess(null, '操作成功');
        } else {
            return $this->buildFailed(ReturnCode::FAILED, '操作失败');
        }
    }

    /**
     * 删除
     * @return array
     */
    public function del()
    {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $where = [];
        $where = $this->addTid($where);
        $where['id'] = $id;

        $done = AdminSubject::destroy($where);
        if ($done) {
            $delWhere = ['sub_id' => $id];
            $delWhere = $this->addTid($delWhere);
            try {
                (new AdminSubjectActive())->where($delWhere)->delete();
                return $this->buildSuccess([]);
            } catch (PDOException $e) {
            } catch (\think\Exception $e) {
            }
        }
        return $this->buildFailed(ReturnCode::DELETE_FAILED, '删除失败');
    }

    /**
     * 获取列表
     * @return array
     * @author chniccs
     */
    public function getList()
    {
        $obj = new AdminSubject();
        $where = [];
        $where = $this->addTid($where);
        try {
            $result = $obj->where($where)->field('id,banner,title,sort')->select();
            return $this->buildSuccess($result);
        } catch (DataNotFoundException $e) {
        } catch (ModelNotFoundException $e) {
        } catch (DbException $e) {
        }
        return $this->buildFailed(ReturnCode::INVALID, '暂无专题');
    }

    /**
     * 获取列表
     * @return array
     * @author chniccs
     */
    public function boundList()
    {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $subId = $this->request->get('sub_id', null);
        $where = ['sub_active.sub_id' => $subId, 'sub_active.tid' => $this->getUserTid()];
        try {
            $sort = AdminSubject::get($subId)->getData('sort');
            $sort = SubjectHelper::getOrderBySort($sort);
            $subsql = Db::table('admin_active_sku sku')->alias('sku')
                ->field('min(lowest_price) as price,sum(sales + init_sales) as sales,vip_discount,aid')
                ->group('aid')
                ->buildSql();
            $listObj = Db::table('admin_subject_active')->alias('sub_active')
                ->where($where)
                ->field('sub_active.sub_id as sub_id,sub_active.tid as tid')
                ->join('admin_actives actives', 'sub_active.goods_id = actives.id')
                ->field('actives.create_time as create_time,actives.id as goods_id,actives.banners as banner,actives.title as title,actives.status as status')
                ->join([$subsql => 'sku'], 'actives.id = sku.aid')
                ->field('sku.price as price,sku.sales as sales,vip_discount')
                ->order($sort)
                ->paginate($limit, false, ['page' => $start])
                ->toArray();
            return $this->buildSuccess([
                'list' => $listObj['data'],
                'count' => $listObj['total']
            ]);
        } catch (DbException $e) {
        };
        return $this->buildFailed(ReturnCode::INVALID, '获取失败');
    }

    public function bind()
    {
        $subId = $this->request->param('sub_id');
        $goods_ids = $this->request->param('goods_ids');
        $where = ['id' => $subId];
        $where = $this->addTid($where);
        if (!AdminSubject::get($where)) {
            return $this->buildFailed(ReturnCode::INVALID, '不存在的专题');
        }

        //创建模型对象
        $model = new AdminSubjectActive();
        //执行新增操作,返回对象数组,数组元素数量与新增数据相同
        //每个对象数据元素，都是一个数据对象$data
        try {
            $where = ['goods_id' => $goods_ids, 'sub_id' => $subId];
            $where = $this->addTid($where);
            $has = $model->where($where)->select()->toArray();
            $hasArr = [];
            if ($has) {
                foreach ($has as $item) {
                    $hasArr[] = $item['goods_id'];
                }
            }
            $dif = array_diff($goods_ids, $hasArr);
            $goodsIds = [];
            foreach ($dif as $id) {
                $goodsIds[] = ['sub_id' => $subId, 'goods_id' => $id, 'tid' => $this->getUserTid()];
            }
            $result = $model
                ->allowField(true)
                ->saveAll($goodsIds);
            if ($result) {
                return $this->buildSuccess(null, '操作成功');
            }
        } catch (Exception $e) {
        }
        return $this->buildFailed(ReturnCode::INVALID, '添加失败');
    }

    public function unbind()
    {
        $subId = $this->request->param('sub_id');
        $ids = $this->request->param('goods_ids');
        $where = ['id' => $subId];
        $where = $this->addTid($where);
        if (!AdminSubject::get($where)) {
            return $this->buildFailed(ReturnCode::INVALID, '不存在的专题');
        }
        try {
            //创建模型对象
            $model = new AdminSubjectActive();
            $where = ['sub_id' => $subId, 'tid' => $this->getUserTid(), 'goods_id' => $ids];
            //要判断这些是不是当前站点的
            $result = $model->where($where)->delete();
            if ($result) {
                return $this->buildSuccess(null, '操作成功');
            }
        } catch (Exception $e) {
        }
        return $this->buildFailed(ReturnCode::INVALID, '操作失败');
    }
}